import BulletMatter from '../Matter/BulletMatter';
import GameInfo from '../../model/GameInfo';
import { BulletStatus } from '../../model/Enums';


export default class GameControl extends Laya.Script{
    /** @prop {name: bullet, tips: '发射的子弹', type: Prefab}*/
    bullet: Laya.Prefab;

    /** @prop {name: ball, tips: '运动的小球', type: Prefab}*/
    ball: Laya.Prefab;

    private ballBox: Laya.Sprite;
    private bulletBox: Laya.Sprite;
    private _time: number = 0;
    private createBallInterval: number = 5000;

    private bulletX: number = 300;
    private bulletY: number = 1000;


    private ballMove: Laya.Sprite;
    private bulletMove: Laya.Sprite;
    private assistantLine = new Laya.Sprite();
    private line: any;

    constructor(){
        super()
    }

    public onAwake(){
        this.ballBox = this.owner.getChildByName('ballBox') as Laya.Sprite;
        this.bulletBox = this.owner.getChildByName('bulletBox') as Laya.Sprite;
        this.createBall();
        this.createBullet();

        GameInfo.instance.on('bulletStatus', this, this.handleBullet);
    } 



    public onEnable(){
       this._time = Date.now();
    }

    public onUpdate(){
        let now = Date.now();
        if(now - this._time > this.createBallInterval){
            this._time = now;
           this.createBall();
        }

        if(this.bulletMove.y < 0){
            // 移除子弹container
            this.bulletMove.removeSelf();
            this.bulletMove.getComponent(BulletMatter).remveFromWord();
            this.createBullet();
        }
    }

    public onMouseMove(event: Laya.Event){
        let mouseX = event.stageX;
        let mouseY = event.stageY;

        let y2 = 500 * (mouseY - this.bulletY) + this.bulletY;
        let x2 = 500 * (mouseX - this.bulletX) + this.bulletX;

        this.assistantLine.graphics.clear();
        this.assistantLine.graphics.drawLine(this.bulletX, this.bulletY, x2, y2, "#ff0000", 3);
        this.owner.addChild(this.assistantLine);
    }

    public onMouseUp(event: Laya.Event){
        console.log('xx mouseup');
        this.assistantLine.graphics.clear();
        if(this.bulletBox._children.length> 0){
            this.bulletMove.getComponent(BulletMatter).setBulletVec(event.stageX, event.stageY);
        }


    }

    public createBall(): void{
        this.ballMove = this.ball.create();
        this.ballBox.addChild(this.ballMove);
    }

    public createBullet(): void{
        this.bulletMove = this.bullet.create();
        // this.bulletMove = Laya.Pool.getItemByCreateFun('bullet', this.bullet.create, this.bullet);
        this.bulletBox.addChild(this.bulletMove);
    }

    public handleBullet(): void{
        this.createBullet();
    }
}